package com.carl.exception;

import com.carl.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice // 监听所有 controller
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        log.error("## ---> @@ 捕捉到全局异常", e);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("url", req.getRequestURL());
        modelAndView.addObject("exception", e);
        modelAndView.setViewName("error");
        return modelAndView;
    }

    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public Result jsonErrorHandler(HttpServletRequest request , MyException exception) {
        // 错误日志处理
        return Result.failReturn(exception.getMessage(), "some data , " + request.getRequestURI());
    }

}
